const jwt = require("jsonwebtoken");
const { JWT_SECRET } = require("../config/default");
const {
  TokenExpiredError,
  InvalidToken,
  hasNoAdminPermission,
} = require("../constant/error");
const auth = async (ctx, next) => {
  const { authorization } = ctx.request.header;
  const token = authorization.replace("Bearer ", "").trim();
  try {
    const user = jwt.verify(token, JWT_SECRET);
    ctx.state.user = user;
  } catch (err) {
    switch (err.name) {
      case "TokenExpiredError":
        return ctx.app.emit("error", TokenExpiredError, ctx);
      case "JsonWebTokenError":
        return ctx.app.emit("error", InvalidToken, ctx);
      default:
        return ctx.app.emit("error", InvalidToken, ctx);
    }
  }

  await next();
};

const hadAdminPermission = async (ctx, next) => {
  const { is_admin } = ctx.state.user;
  if (!is_admin) {
    return ctx.app.emit("error", hasNoAdminPermission, ctx);
  }
  await next();
};
module.exports = {
  auth,
  hadAdminPermission,
};
